﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;

namespace TopShooter
{
	public abstract partial class UnitCommand
	{
		public class Move : UnitCommand
		{
			public Vector2 TargetLocation;
			public float DistanceRemaining;
			private float _timeRemaining;
			public Vector2 Direction;
			private float _adjustedSpeed;
			

			

			public Move(Vector2 targetLocation)
			{
				TargetLocation = targetLocation;
			}

			public override float TimeRemaining
			{
				get { return _timeRemaining; }
			}
			protected override void _OnStarted()
			{
				base._OnStarted();
				_CalculateMovement();
			}
			protected override float OnUpdate(float time)
			{
				Owner.Direction = Direction;
				if (time >= TimeRemaining)
				{
					_CalculateMovement();
					
					if (time >= TimeRemaining)
					{
						if (_adjustedSpeed > 0)
						{
							Owner.Location = TargetLocation;
						}
						float timeunused = time - TimeRemaining;
						_timeRemaining = 0;
						return timeunused;
					}
				}
				_adjustedSpeed = (Owner.MovementSpeed - Owner.Armor.Weight);
				if (_adjustedSpeed > 0)
				{
					Vector2 offset = Direction * time * _adjustedSpeed;

					Owner.Location += offset;
					_timeRemaining -= time;
					return 0;
				}
				else
					return time;
			}

			public override void Attach(Unit owner)
			{
				base.Attach(owner);
				_CalculateMovement();
			}

			private void _CalculateMovement()
			{
				float dx = TargetLocation.X - Owner.Location.X;
				float dy = TargetLocation.Y - Owner.Location.Y;
				DistanceRemaining = (float)Math.Sqrt((dx * dx) + (dy * dy));
				Direction = new Vector2(dx / DistanceRemaining, dy / DistanceRemaining);
				_adjustedSpeed = (Owner.MovementSpeed - Owner.Armor.Weight);
				if (_adjustedSpeed <= 0)
				{
					_timeRemaining = 0;
					return;
				}
				_timeRemaining = DistanceRemaining / _adjustedSpeed;
				
				
			}
		}
	}
}
